package com.hunt.system.token;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.fasterxml.jackson.databind.ObjectMapper;

public class JWTUtil {

	private static final String SECRET = "XX#$%()(#*!()!KL<><MQLMNQNQJQK sdfkjsdrow32234545fdf>?N<:{LWPW";

	private static final String EXP = "exp";

	private static final String PAYLOAD = "payload";

	/**
	 * get jwt String of object
	 * 
	 * @param object
	 *            the POJO object
	 * @param maxAge
	 *            the milliseconds of life time
	 * @return the jwt token
	 */
	public static <T> String sign(T object, long maxAge) {
		try {

			Date expiresAt = new Date(System.currentTimeMillis() + maxAge);
			Boolean isVip = null;
			String name = null;
			ObjectMapper mapper = new ObjectMapper();
			String jsonString = mapper.writeValueAsString(object);
			String token = JWT.create().withIssuer("auth0").withClaim("isVip", isVip).withClaim("name", name)
					.withExpiresAt(expiresAt).withSubject(jsonString).sign(Algorithm.HMAC256(SECRET));
			return token;
		} catch (Exception e) {
			return null;
		}
	}

	/**
	 * get the object of jwt if not expired
	 * 
	 * @param jwt
	 * @return POJO object
	 */
	public static <T> T unsign(String token, Class<T> classT) {
		// final JWTVerifier verifier = new JWTVerifier(SECRET);
		ObjectMapper mapper = new ObjectMapper();
		String subject = null;
		T t = null;
		try {
			JWTVerifier verifier = JWT.require(Algorithm.HMAC256(SECRET)).withIssuer("auth0").build();
			DecodedJWT jwt = verifier.verify(token);
			subject = jwt.getSubject();
			t = mapper.readValue(subject, classT);
		} catch (IOException e) {
			e.printStackTrace();
		} catch (IllegalArgumentException e1) {
			e1.printStackTrace();
		}
		return t;
	}
}
